/**
 * Copyright &copy; 2016-2017 <a href="https://www.lczyfz.com">联创智云</a> All rights reserved.
 */
package com.lczyfz.campusinfo.modules.user.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.lczyfz.campusinfo.modules.user.utils.PropertiesUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.drew.lang.StringUtil;
import com.lczyfz.campusinfo.common.persistence.Page;
import com.lczyfz.campusinfo.common.service.CrudService;
import com.lczyfz.campusinfo.common.utils.ApiResultUtils;
import com.lczyfz.campusinfo.common.utils.Const;
import com.lczyfz.campusinfo.common.utils.IdGen;
import com.lczyfz.campusinfo.common.utils.StringUtils;
import com.lczyfz.campusinfo.modules.campusinfo.dao.CampusinfoSchoolDao;
import com.lczyfz.campusinfo.modules.campusinfo.entity.CampusinfoSchool;
import com.lczyfz.campusinfo.modules.frontuser.entity.CampusinfoFrontUser;
import com.lczyfz.campusinfo.modules.frontuser.utils.FrontUserUtils;
import com.lczyfz.campusinfo.modules.sys.entity.User;
import com.lczyfz.campusinfo.modules.sys.security.FormAuthenticationFilter;
import com.lczyfz.campusinfo.modules.sys.security.SystemAuthorizingRealm;
import com.lczyfz.campusinfo.modules.sys.security.UsernamePasswordToken;
import com.lczyfz.campusinfo.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.lczyfz.campusinfo.modules.sys.service.SystemService;
import com.lczyfz.campusinfo.modules.sys.utils.UserUtils;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoGroupDao;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoUserDao;
import com.lczyfz.campusinfo.modules.user.dao.CampusinfoUserGroupDao;
import com.lczyfz.campusinfo.modules.user.utils.SendMsg;
import com.lczyfz.campusinfo.modules.user.utils.ServerResponse;
import com.sun.tools.corba.se.idl.constExpr.And;

/**
 * 用户信息Service
 * @author 陈维乾
 * @version 2018-03-31
 */
@Service
@Transactional(readOnly = true)
public class CampusinfoUserService extends CrudService<CampusinfoUserDao, User> {

	@Autowired
	CampusinfoUserDao campusinfoUserDao;
	
	@Autowired
	CampusinfoUserGroupDao campusinfoUserGroupDao;
	
	@Autowired
	CampusinfoGroupDao campusinfoGroupDao;
	
	@Autowired
	CampusinfoSchoolDao campusinfoSchoolDao;

	//手机正则表达式
	public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
	
	
    /**
     * 根据登录名前端用户
     */
    public User getUserByLoginName(String loginName) {
        return UserUtils.getByLoginName(loginName);
    }
	
	public User get(String id) {
		return super.get(id);
	}
	
	public List<User> findList(User user) {
		return super.findList(user);
	}
	
	public Page<User> findPage(Page<User> page, User user) {
		return super.findPage(page, user);
	}
	public Page<User> findUserGroupPage(Page<User> page, User user) {
		user.setPage(page);
		List<User> users = dao.findList(user);
		
		
		for(User user1:users){
			if(user1.getGroupId() != null && StringUtils.isNotBlank(user1.getGroupId())){
				String Id = user1.getGroupId();
				String[] ids = Id.split(",");
				String groupnames = "";
				
				for(String id:ids){
					groupnames += campusinfoGroupDao.findNameById(id)+"、";
					
				}
				user1.setGroupName(groupnames);
			}	
		}
		page.setList(users);
		
		return page;
		
	}
	
	
	@Transactional(readOnly = false)
	public void save(User user) {
		super.save(user);
	}
	@Transactional(readOnly = false)
	public void saveUserAndUserGroup(User user) {
		
		super.save(user);
	}
	
	
	@Transactional(readOnly = false)
	public void delete(User user) {
		super.delete(user);
	}
	
	public List<User> findAllList(User user) {
		return campusinfoUserDao.findAllList(new User());
	}
	
	public User getByIdAndGroupid(String id,String groupId){
		return campusinfoUserDao.getByIdAndGroupid(id,groupId);
	}
	
	public ServerResponse<String> login(HttpServletRequest request){
		
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		
		
		UserUtils.getSubject().logout();
		if(principal != null){
			return ServerResponse.createBySuccessMessage("用户已登录");
		}


        String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);


        String password = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);


        String type = request.getParameter("type").toString();

		
        Subject currentUser = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, type);

        currentUser.login(token);
		
		return ServerResponse.createByErrorMessage("登录失败");
	}
	
	//获取所有用户
	public List<User> findAllUser(){
		return campusinfoUserDao.findAllUser();
	}
	//判断用户名是否存
	public ServerResponse<String> isUserName(String userName){
		 return this.checkValid(userName,Const.LOGINNAME);
	}
	//判断邮箱是否存
	public ServerResponse<String> isEmail(String email){
		 return this.checkValid(email,Const.EMAIL);
	}
	
	
	@Transactional(readOnly = false)
	//TODO用户注册
	public ServerResponse<String> register(User user,String verifyNum,HttpServletRequest request){

        //先判断用户名是存在
        ServerResponse<String> validResponse = this.checkValid(user.getLoginName(),Const.LOGINNAME);
        if(!validResponse.isSuccess()){
        	return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!validResponse.isSuccess()){
            return validResponse;
        }
        System.err.println(verifyNum);
        String SessionVerifyNum = (String)request.getSession().getAttribute("VERIFYNUM");
        String moblie = (String)request.getSession().getAttribute("MOBILE");
        System.err.println(SessionVerifyNum);
        System.err.println(moblie);
        System.err.println(request.getSession());
        System.err.println(UserUtils.getSession());
        if(SessionVerifyNum == null){
        	return ServerResponse.createByErrorMessage("验证码失效");
        }
        if(!SessionVerifyNum.equalsIgnoreCase(verifyNum)){
        	return ServerResponse.createByErrorMessage("验证码不正确");
        }
        if(!moblie.equals(user.getMobile())){
        	return ServerResponse.createByErrorMessage("注册手机与验证码手机不一致");
        }
        
        //TODO 给密码加密
        String password =  SystemService.entryptPassword(user.getPassword());
 
        user.preInsert();
        user.setPassword(password);
        user.setLoginFlag("1");
        user.setStatus("0");
        user.setUserType("1");
        int resultCount = campusinfoUserDao.insetUser(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
    	//清空验证码
    	UserUtils.getSession().setAttribute("VERIFYNUM", IdGen.uuid());
        return ServerResponse.createBySuccessMessage("注册成功");
        
	}
	//短信验证手机号
	public ServerResponse<String> verifyBySendMsg(String mobile ,HttpServletRequest request){
		//先判断手机号的正确性
		Boolean flag = Pattern.matches(REGEX_MOBILE, mobile);
		if(!flag){
			return ServerResponse.createByErrorMessage("输入的手机号码不正确");
		}
		String verifyNum = SendMsg.SendMsg(mobile);
		

		String VALIDTIME= PropertiesUtil.getProperty("VALIDTIME");

//		UserUtils.getSession().setAttribute("VERIFYNUM",verifyNum);
//		UserUtils.getSession().setAttribute("MOBILE", mobile);
		
		request.getSession().setAttribute("VERIFYNUM",verifyNum);
		request.getSession().setAttribute("MOBILE", mobile);
		
		request.getSession().setMaxInactiveInterval(Integer.parseInt(VALIDTIME)*60);
		
		System.err.println(request.getSession().getAttribute("VERIFYNUM"));
		System.err.println(request.getSession());
		System.err.println(request.getSession());
		return ServerResponse.createBySuccessMessage("验证码已发送");
	}
	
	
	//TODO 检查当前是否有用户登录
	
	public ServerResponse<String> hasUser(){
		Principal principal = UserUtils.getPrincipal();
		if(principal != null){
			return ServerResponse.createBySuccessMessage("用户已登录");
		}
		return ServerResponse.createByErrorMessage("用户未登录");
	}
	
	
	//TODO 获取用户信息
	
	public ServerResponse<User> getUserInfo(){
		
		User user = null;
		
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal!=null){
			user = get(principal.getId());
		}
		
		
		if(user != null){
			
			String schoolname = campusinfoSchoolDao.getById(user.getCollegeId());
			
			user.setSchoolName(schoolname);
			
			return ServerResponse.createBySuccess(user);
		}
		return ServerResponse.createByErrorMessage("用户未登录,无法获取当前用户的信息");
	}
	
	//TODO 忘记密码
	
	//TODO 检查登录用户名/邮箱是否存在
	public ServerResponse<String> checkValid(String str,String type){
		if(StringUtils.isNotBlank(type)){
			if(Const.LOGINNAME.equals(type)){
				int resultCount = campusinfoUserDao.checkLoginName(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("用户名已存在");
				}
			}
			if(Const.EMAIL.equals(type)){
				int resultCount = campusinfoUserDao.checkEamil(str);
				if(resultCount > 0){
					return ServerResponse.createByErrorMessage("邮箱已存在");
				}
			}
		}else{
			return ServerResponse.createByErrorMessage("参数错误");
		}
		return ServerResponse.createBySuccessMessage("校验成功");
	}
	@Transactional(readOnly = false)
	public ServerResponse<String> forgetResetPassword(String loginName,String passwordNew){
		
        ServerResponse<String> validrResponse = this.checkValid(loginName, Const.LOGINNAME);
        if (validrResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        //加密
        String password =  SystemService.entryptPassword(passwordNew);
      
        
		int rowCount = campusinfoUserDao.updatePasswordByloginName(loginName,password);
        if(rowCount > 0){
        	 return ServerResponse.createBySuccessMessage("修改密码成功");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
	}
	@Transactional(readOnly = false)
	public ServerResponse<String> resetPassword(String passwordOld,String passwordNew){
		
		//先获取User 然后同loginName 判断密码是否正确
		User user = UserUtils.getUser();
		//加密
		Boolean falg = SystemService.validatePassword(passwordOld,user.getPassword());
        if (!falg) {
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        String password =  SystemService.entryptPassword(passwordNew);
    	int resultcount = campusinfoUserDao.updatePasswordByloginName(user.getLoginName(), password);
        if(resultcount == 0 ){
        	return ServerResponse.createByErrorMessage("密码更新失败");
        }
    	return ServerResponse.createBySuccessMessage("密码更新成功");

	}
	@Transactional(readOnly = false)
	public ServerResponse<User> updateInformation(User user){
		
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal == null){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		if((user.getSchoolId() == null ||  StringUtils.isNotEmpty(user.getSchoolId())) &&
				(user.getStuId() == null || StringUtils.isNotEmpty(user.getStuId())) &&
				(user.getName() == null || StringUtils.isNotEmpty(user.getName())) &&
				(user.getMobile() == null || StringUtils.isNotEmpty(user.getMobile())) &&
				(user.getEmail() == null || StringUtils.isNotEmpty(user.getEmail()))){
			return ServerResponse.createByErrorMessage("输入的值不能为空");
		}

		User currentUser = (User)UserUtils.getUser();

		//username不能被更新，，email也需要校验，如果email相同，不能是当前用户的
		user.setId(currentUser.getId());
		user.setLoginName(currentUser.getLoginName());
		user.preUpdate();
		
		if(user.getEmail() != null && user.getEmail() != ""){
			int resultCount = campusinfoUserDao.checkEmailByUserId(user.getEmail(),currentUser.getId());
	        if (resultCount > 0){
	            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
	        }
		}
        int updateCount = campusinfoUserDao.updateUserInfo(user);
        if(updateCount > 0){
        	return ServerResponse.createBySuccess("更新个人信息成功", user);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
	}
	public ServerResponse<String> isVerifyUser(){
		SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
		if (principal == null){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		User currentUser = UserUtils.getUser();
		
		System.err.println(currentUser);

		int resultCount = campusinfoUserDao.checkVerifyUser(currentUser);
		if(resultCount>0){
			return ServerResponse.createBySuccessMessage("用户已实名");
		}
		return ServerResponse.createByErrorMessage("用户未实名");
	}
	
	
}